package TP2.sorters;


import anaydis.sort.Sorter;
import anaydis.sort.SorterType;
import anaydis.sort.gui.ObservableSorter;
import anaydis.sort.gui.SorterListener;
import com.sun.istack.internal.NotNull;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
//import org.jetbrains.annotations.NotNull;

public abstract class AbstractSorter implements Sorter, ObservableSorter {
    private SorterType type;
    private ArrayList<SorterListener> sorterListenerList;

    protected  AbstractSorter (){}

    protected  AbstractSorter (SorterType type){
        this.type=type;
        sorterListenerList = new ArrayList();
    }

    protected <T> boolean greater(Comparator<T> c, List<T> list, int i, int j){
        for(int w = 0; w < sorterListenerList.size(); w++){
            sorterListenerList.get(w).greater(i,j);
        }
        return c.compare(list.get(i), list.get(j)) > 0;
    }

    protected <T> boolean equals(Comparator<T> c, List<T> list, int i, int j){
        for(int w = 0; w < sorterListenerList.size(); w++){
            sorterListenerList.get(w).equals(i,j);
        }
        return c.compare(list.get(i), list.get(j)) == 0;
    }

    protected <T> void swap(List<T> list, int i, int j){
        for(int w = 0; w < sorterListenerList.size(); w++){
            sorterListenerList.get(w).swap(i,j);
        }
        list.set(j, list.set(i, list.get(j)));
    }

    protected <T> boolean greater(Locale loc, Comparator<T> c, List<T> list, int i, int j) {
        for (SorterListener sorterListener : sorterListenerList) {
            sorterListener.greater(i, j);
        }
        Collator collator = Collator.getInstance(loc);
        return collator.compare(list.get(i), list.get(j)) > 0;
    }

    public SorterType getType() {
        return type;
    }

    public void addSorterListener(@NotNull SorterListener sorterListener) {
         sorterListenerList.add(sorterListener);
     }

    public void removeSorterListener(@NotNull SorterListener sorterListener) {
        sorterListenerList.remove(sorterListener);
    }
}